//
//  VmixVideoTableViewController.m
//  VmixMobileDemo
//
//  Created by jeffs on 6/16/10.
//  Copyright 2010 VMIX Media. All rights reserved.
//

#import "VmixVideoTableViewController.h"
#import <MediaPlayer/MediaPlayer.h>


@implementation VmixVideoTableViewController
@synthesize mediasList, collection, oppQueue, getCollectionMediasOperation, videoCell, authData, imageCache, appLaunched, video;

#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
   // self.clearsSelectionOnViewWillAppear = NO;
	self.navigationItem.title = self.collection.name;
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_center_large_gray.png"]];
	self.tableView.backgroundColor = [UIColor clearColor];
	self.tableView.separatorColor = [UIColor grayColor];
    
	self.mediasList = [[NSMutableArray alloc] init];
	self.imageCache = [[NSMutableDictionary alloc] init];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	//Setup operation queue to spin up non blocking execution thread.
	self.oppQueue = [[NSOperationQueue alloc] init];
	self.getCollectionMediasOperation = [[GetCollectionMediasOperation alloc] init];
	NSString *collectionMediasApi = [NSString stringWithFormat:@"%@action=getCollectionMedias&collection_id=%@&atoken=%@&output=xml", COLLECTION, collection.collection_id, ATOKEN];
	self.getCollectionMediasOperation.collectionMediasApi =  collectionMediasApi;
	self.getCollectionMediasOperation.delegate = self;
	[oppQueue addOperation:self.getCollectionMediasOperation];
	[self.getCollectionMediasOperation release];
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source
/*
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}
*/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	int count = [self.mediasList count];
    if (count == 0)
	{
        return 1;
    }
    return count;
}


- (void)fetchImage:(NSArray *)args {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    UIImageView *iv = [args objectAtIndex:0];
    NSString *str = [args objectAtIndex:1];
    NSURL *imageUrl = [NSURL URLWithString:str];
    NSURLRequest *imageReq = [NSURLRequest requestWithURL:imageUrl];
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *imageData = [NSURLConnection sendSynchronousRequest:imageReq returningResponse:&response error:&error];
    UIImage *theImage = [UIImage imageWithData:imageData];
    [self.imageCache setObject:theImage forKey:str];
	if (iv.tag == [[args objectAtIndex:2] intValue]) {
	[iv setImage:theImage];
	}
    [pool release];
}

- (UIImage *)getImageForURL:(NSString *)str inImageView:(UIImageView *)iv {
    UIImage *i = nil;
    if ([self.imageCache objectForKey:str] != nil) {
        i = [self.imageCache objectForKey:str];
    } else {
        i = [[UIImage alloc] init];
        NSArray *args = [NSArray arrayWithObjects:iv, str, [NSNumber numberWithInt:iv.tag], nil];
        [self performSelectorInBackground:@selector(fetchImage:) withObject:args];
		
    }
    return i;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
  	static NSString *CellIdentifier = @"Cell";
	static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";
    
    // add a placeholder cell while waiting on table data
    int nodeCount = [self.mediasList count];
	
	if (nodeCount == 0 && indexPath.row == 0)
	{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		
		cell.detailTextLabel.text = @"Loading…";
		
		return cell;
    }
    
	
	VideoCell *cell = (VideoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		NSLog(@"Loading cell from NIB");
		[[NSBundle mainBundle] loadNibNamed:@"VideoCell" owner:self options:nil];
		cell = videoCell;
	}else {
		// mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
    }
	
	if(self.video== nil){
		VmixVideo *v = [[VmixVideo alloc] init];
		self.video = v;
	}
	self.video = [self.mediasList objectAtIndex:indexPath.row];
	
	cell.titleLabel.text = self.video.title;
	cell.descriptionText.text = self.video.description;
	
	NSString *path = self.video.thumbnail;
	NSString *imgMan = [NSString stringWithFormat:@"http://cdn-aki.vmixcore.com/imgman.jpg?fill=000000000&url=%@&width=216&height=120", path];
	cell.videoImageView.tag = indexPath.row + 1000;
	cell.videoImageView.image = [self getImageForURL:imgMan inImageView:cell.videoImageView];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	if ((indexPath.row % 2) != 0){
		cell.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.05];
	}
	
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	

	VmixVideo *v = (VmixVideo *) [self.mediasList objectAtIndex:indexPath.row];

	NSString *mediaPlay = [NSString stringWithFormat:@"%@token=%@&output=xml", PLAY, v.token];
	NSURL *url = [NSURL URLWithString: mediaPlay];
	CXMLDocument *playParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
	CXMLNode *firstNode = [playParser childAtIndex:0];
	NSURL *playUrl = [NSURL URLWithString: [firstNode getElementValue:@"file" error:nil]];
	
	if([[[UIDevice currentDevice] systemVersion] doubleValue] >= 3.2){
		
		MPMoviePlayerViewController * mpViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:playUrl];
		mpViewController.moviePlayer.shouldAutoplay = NO;
		mpViewController.view.backgroundColor = [UIColor blackColor];
		[self modalViewController].view.backgroundColor = [UIColor blackColor];
		[self presentMoviePlayerViewControllerAnimated:mpViewController];
		//[mpViewController.moviePlayer play];
		[mpViewController release];
		
	}else{
		MPMoviePlayerController *moviePlayer;
		moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:playUrl];
		moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
		[moviePlayer play];
	}
	
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 100.0f;
}

//Delegate method to comply with GetMediaListOperationDelegate
- (void)didFinishParsingCollectionMedias:(NSMutableArray *) mediaArray{
	
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	self.mediasList = mediaArray;
	[self performSelectorOnMainThread:@selector(reloadTableData)
						   withObject:nil waitUntilDone:NO];
	
}

- (void) reloadTableData{
	
	[self.tableView reloadData];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

